﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using PSE.Deployment.SetupBase.Configuration;
using PSE.Deployment.SetupBase.Parameter;
using PSE.Deployment.Engine.CustomExceptions;
using PSE.Deployment.Engine.Interfaces;

namespace PSE.Deployment.SetupBase.Steps
{
    public class StartWindowsService : SetupStep<Configuration.Actions.InstallWindowsService>
    {
        public bool Start { get; set; }

        public StartWindowsService(IStepGroup parent, Group group, Configuration.Actions.InstallWindowsService action, Parameter.Enums.SetupMode setupMode, bool start)
            : base(parent, group, action, setupMode)
        {
            this.Start = start;
            this.ResetProgress(Action.Services.Count);
        }

        public override void Execute()
        {
            this.ResetProgress(Action.Services.Count);

            if (this.SetupMode == Parameter.Enums.SetupMode.Install)
            {
                StartStopServices();
            }
        }

        public override void Undo()
        {
            
        }

        private void StartStopServices()
        {
            foreach (WindowsService service in Action.Services)
            {
                if (this.IsStopped())
                    return;

                this.IncrementProgress(service.DisplayName);

                if (Start)
                {
                    if (service.ServiceName == SetupMainFactory.GetInstance().HosterName)
                        PSE.Deployment.Util.WindowsServiceController.Start(service.ServiceName, new string[] { "false" });
                    else
                        PSE.Deployment.Util.WindowsServiceController.Start(service.ServiceName);
                }
                else
                {
                    PSE.Deployment.Util.WindowsServiceController.Stop(service.ServiceName);
                }
            }
        }
    }
}
